package com.edu.html.interceptor;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.edu.common.constant.CONSTANT;
import com.edu.html.pojo.Menu;
import com.edu.html.pojo.Permission;
import com.edu.html.pojo.User;
import com.edu.html.service.PermissionService;

public class PermissionInterceptor implements HandlerInterceptor{
	
	private static Logger logger = Logger.getLogger(PermissionInterceptor.class);
	
	@Autowired
	private PermissionService permissionService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.info("Msg:1.开始加载权限资源。"+JSON.toJSONString(request.getParameterMap()));
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		logger.info("Msg:2.开始加载权限资源。");
		Subject us = SecurityUtils.getSubject();
		if (!us.isAuthenticated()) {
			logger.info("Msg:未登录，无法加载权限资源。");
			return;
		}
		Session session = SecurityUtils.getSubject().getSession(); 
		User user = (User) session.getAttribute(CONSTANT.SESSION_USER_KEY);
		if(user == null || StringUtils.isEmpty(user.getRole())){
			logger.info("Msg:SESSION中用户未找到");
			return;
		}
		Permission permission = permissionService.queryMenus(user.getRole());
		if(permission != null){
			String menuIds = permission.getMenuIds();
			List<Menu> menus = permissionService.selectMenuByIds(menuIds);
			for(Menu menu : menus){
				if(menu.getParentId() == null || menu.getParentId() == 0){
					List<Menu> childMenus = new ArrayList<Menu>();
					for(Menu child : menus){
						if(child.getParentId() == menu.getId()){
							childMenus.add(child);
						}
					}
					menu.setChildMenus(childMenus);
				}
			}
			permission.setMenus(menus);
			session.setAttribute(CONSTANT.SESSION_PERMISSION_KEY, permission);
			logger.info("Msg:加载权限资源,"+JSON.toJSONString(permission));
		}else{
			logger.info("Msg:未找到权限资源，"+user.getRole());
		}
	}

}
